package edu.jsnu.purchase.ticket.service.impl;

import edu.jsnu.purchase.ticket.service.UserService;
import edu.jsnu.service.ticket.order.dao.OrderMapper;
import edu.jsnu.service.ticket.order.domain.Order;
import edu.jsnu.service.ticket.seat.dao.SeatMapper;
import edu.jsnu.service.ticket.seat.domain.Seat;
import edu.jsnu.service.ticket.user.dao.UserMapper;
import edu.jsnu.service.ticket.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Override
    public User getUserInfoByName(String userName) {
        User user = userMapper.selectByName(userName);
        return user;
    }

    @Override
    public User register(String userName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        //角色id  1：管理员  2：用户
        user.setRoleId(2);
        user.setBalance(100.0);
        user.setOperatorTime(new Date());
        Integer result = userMapper.insertSelective(user);
        if (result > 0) {
            return user;
        }
        return null;
    }

    @Override
    public Boolean paySuccess(Integer orderId, Integer userId, Double money, String seatNumber, Integer scheduleId) {
        Double balance = userMapper.getBalanceById(userId);
        if (balance >= money) {
            if (userMapper.updateBalance(userId, balance - money) > 0){
                Order order = new Order();
                order.setId(orderId);
                order.setPayTime(new Date());
                order.setStatus(1);//0未支付，1已支付，2订单关闭
                orderMapper.updateByPrimaryKeySelective(order);
                //插入座位表
                for (String seatStr : seatNumber.split(",")
                     ) {
                    Seat seat = new Seat();
                    seat.setScheduleId(scheduleId);
                    seat.setSeatId(Integer.valueOf(seatStr));
                    seat.setOrderId(orderId);
                    seatMapper.insertSelective(seat);
                }
                return true;
            }
        }
        else {
            return false;
        }
        return false;
    }

    @Override
    public User getUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public Integer updateUser(User user) {
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User recharge(Integer userId, Double money) {
        Integer result = userMapper.updateBalance(userId, userMapper.selectByPrimaryKey(userId).getBalance() + money);
        User user = userMapper.selectByPrimaryKey(userId);
        return user;
    }
}
